<template>
  <div class="page">
    <header class="header">
      <FanPageHeader
        subTitle="用户中心"
        current="返回首页"
        :img="karina8"
        :title="userStore.userInfo.username"
      />
      <!-- Waves 放在header内部，覆盖在图片下部分 -->
      <div class="waves-wrapper">
        <Waves height="6rem" />
      </div>
    </header>

    <!-- 个人信息中心 -->
    <main class="content">
      <a-tabs v-model:activeKey="activeKey">
        <!-- 个人信息标签页 -->
        <a-tab-pane key="1" tab="个人信息">
          <span>用户头像：</span>
          <fan-avatar
            :avatarUrl="userStore.userInfo.avatar"
            @update:avatarUrl="handleAvatarUpdate"
          ></fan-avatar>
          <div class="userInfo">
            <div class="userInfo-item">
              <span>你的昵称：</span>
              <span class="nickname" v-if="!isEditUserName">{{
                userStore.userInfo.username
              }}</span>
              <div v-else>
                <a-input
                  v-model:value="editUserName"
                  size="small"
                  class="nickname-input"
                >
                </a-input>
              </div>
            </div>
            <div class="userInfo-item">
              <a-button
                type="default"
                @click="changeUserName"
                v-if="!isEditUserName"
                >修改昵称</a-button
              >
              <a-button
                type="info"
                @click="confirmChangeUsername"
                :loading="confirmLoading"
                v-else
                >确认修改</a-button
              >
              <a-button type="primary" v-if="!isEditUserName" @click="logout"
                >退出登录</a-button
              >
              <a-button type="primary" v-else @click="cancelChangeUsername"
                >取消修改</a-button
              >
            </div>
          </div>
        </a-tab-pane>

        <!-- 密码修改标签页 -->
        <a-tab-pane key="2" tab="密码修改">
          <div> 
            <a-form
        :rules="rules"
            ref="formRef"
            name="custom-validation"
            layout="vertical"
            :model="formState"
            @finish="handleFinish"
          >
            <a-form-item has-feedback label="原密码：" name="pass">
              <a-input v-model:value="formState.pass" type="password" autocomplete="off" />
            </a-form-item>
            <a-form-item has-feedback label="新密码：" name="checkPass">
              <a-input v-model:value="formState.checkPass" type="password" autocomplete="off" />
            </a-form-item>
            <a-form-item has-feedback label="确认新密码：" name="confirmCheckPass">
              <a-input v-model:value="formState.confirmCheckPass" type="password" autocomplete="off" />
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 24 }" style="text-align: center;">
              <a-button type="primary" html-type="submit">提交修改</a-button>
              <a-button style="margin-left: 10px" @click="resetForm">重置表单</a-button>
            </a-form-item>
          </a-form>
          </div>
        </a-tab-pane>
      </a-tabs>
    </main>
  </div>

  <a-modal
    v-model:visible="visible"
    title="退出登录"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
  >
    <p>{{ "您要确认退出登录吗？" }}</p>
  </a-modal>
</template>

<script setup>
import karina8 from "@/assets/wrapper/karina8.png";
import { useUserStore } from "../../stores/user";
import { useRouter } from "vue-router";
import FanPageHeader from "../../components/common/FanPageHeader.vue";
import Waves from "@/components/common/waves.vue";
import { ref, onMounted, reactive } from "vue";
import FanAvatar from "../../components/common/FanAvatar.vue";
import { FanNotification } from "../../libs/util.toast";

const userStore = useUserStore();
const router = useRouter();
// 标签页状态
const activeKey = ref("1");
// 弹窗状态
const visible = ref(false);
// 加载状态
const confirmLoading = ref(false);
// 表单引用
const formRef = ref();
//点击退出登录  唤醒弹窗
const logout = () => {
  visible.value = true;
};
const editUserName = ref("");
const isEditUserName = ref(false);
const formState = reactive({
  pass: "", // 原密码
  checkPass: "", // 新密码
  confirmCheckPass: "", // 确认新密码
});

// 表单验证规则
const rules = {
  pass: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 5, max: 15, message: '密码长度应为5-15个字符', trigger: 'blur' }
  ],
  checkPass: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 5, max: 15, message: '密码长度应为5-15个字符', trigger: 'blur' }
  ],
  confirmCheckPass: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { min: 5, max: 15, message: '密码长度应为5-15个字符', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value !== formState.checkPass) {
          return Promise.reject('两次输入的新密码不一致');
        }
        return Promise.resolve();
      },
      trigger: 'blur'
    }
  ]
};

const handleOk = async () => {
  confirmLoading.value = true;
  try {
    const res = await userStore.LogoutPinia();
    if (res.success) {
      FanNotification.success("退出登录成功");
      visible.value = false;
      router.push("/index");
    } else {
      FanNotification.error(res.data?.message || "退出登录失败");
      visible.value = false;
    }
  } catch (error) {
    FanNotification.error(error.message || "退出登录失败");
  } finally {
    confirmLoading.value = false;
  }
};

const getUserInfo = async () => {
  try {
    const res = await userStore.getUserInfoPinia();
    if (res.success) {
      FanNotification.success("初始化用户信息成功");
      editUserName.value = userStore.userInfo.username;
    }

    // TODO  进入界面处理用户信息
  } catch (error) {
    FanNotification.error(error.message || "初始化用户信息失败");
  }
};
// 编辑昵称
const changeUserName = () => {
  isEditUserName.value = !isEditUserName.value;
};
// 确认修改昵称
const confirmChangeUsername = async () => {
  confirmLoading.value = true;
  try {
    const res = await userStore.changeUserName({
      username: editUserName.value,
    });
    if (res.success) {
      FanNotification.success("修改昵称成功");
      getUserInfo();
      isEditUserName.value = false;
    } else {
      FanNotification.error(res.message || "修改昵称失败");
    }
    confirmLoading.value = false;
  } catch (error) {
    FanNotification.error(error.message || "修改昵称失败");
    confirmLoading.value = false;
  }
};
// 取消修改昵称
const cancelChangeUsername = () => {
  isEditUserName.value = false;
};
// 处理头像更新
const handleAvatarUpdate = (newAvatarUrl) => {
  userStore.updateAvatar(newAvatarUrl);
};

// 表单提交处理
const handleFinish = async (values) => {
  try {
    const data = {
      password: values.pass, // 原密码
      newPassword: values.checkPass // 新密码
    };
    
    // 调用API修改密码
    const res = await userStore.changePassword(data);
    
    if (res.success) {
      FanNotification.success('密码修改成功');
      resetForm(); // 重置表单
      // 可选：退出登录让用户重新登录
      // await handleOk();
    } else {
      FanNotification.error(res.data?.message || '密码修改失败');
    }
  } catch (error) {
    FanNotification.error(error.message || '密码修改失败');
  }
};


// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
};
onMounted(() => {
  getUserInfo();
});
</script>

<style scoped>
/* 页面整体布局 */
.page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* Header 样式 */
.header {
  position: relative;
  width: 100%;
  flex-shrink: 0;
}

/* Waves 包装器 - 确保波浪只覆盖图片下部分 */
.waves-wrapper {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 10rem;
  pointer-events: none; /* 确保不拦截鼠标事件 */
}

/* 主要内容区域 - 居中显示 */
.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}
.userInfo {
  margin-top: 0/8rem;
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.userInfo-item {
  display: flex;
  align-items: center;
}
</style>
